package com.itheima.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/*
ACK机制
1 设置手动签收 配置文件监听容器中设置 acknowledge="manual"
2.让监听器实现MessageListener子接口 ChannelAwareMessageListener
3.如果消息成功处理，则调用channel的 basicAck()签收 如果消息处理失败则调用channel的basicNack（）拒绝签收,broker重新发送
 */
@Component
public class AckListener implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        //消息的tag
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //接收消息
            System.out.println(new String(message.getBody()));
            //处理业务逻辑
            System.out.println("处理业务逻辑");
            //模拟异常
            int i=3/0;
            //手动签收  tag  是否接送多条消息
            channel.basicAck(deliveryTag,true);
        }catch (Exception e){
            System.out.println("异常出现了，准备重新发送消息");
            //拒绝签收   tag   是否接送多条消息  是否重新发送
            channel.basicNack(deliveryTag,true,true);
        }

    }
}
